/**
 * 
 */
package com.istart.webmagic.guba;

import java.util.ArrayList;
import java.util.List;

import com.istart.webmagic.HtmlUtil;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * 获取评论表：评论ID、评论人、影响力、吧龄、评论时间、评论内容、被赞数
 */
public class GuBaCommentPageProcessor implements PageProcessor {
	//http://guba.eastmoney.com/default_1.html
	//文章列表
    public static final String URL_LIST = "http://guba\\.eastmoney\\.com/default_\\d+\\.html";
//    http://guba.eastmoney.com/news,gssz,257496576.html
//    http://guba.eastmoney.com/news,zsgjgdaxi,257494345.html
    //文章内容
    public static final String URL_POST = "http://guba\\.eastmoney\\.com/news,\\w+,\\d+\\.html";

    public static final String URL_NEXT = "default_\\d+\\.html";
    
    //文字评论
    public static final String URL_COMMENT = "http://guba\\.eastmoney\\.com/news,\\w+,\\d+_\\d+\\.html";
    private Site site = Site
            .me()
            .setDomain("guba.eastmoney.com/")
            .setSleepTime(3000)
            .setUserAgent(
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
    @Override
    public void process(Page page) {
        if (page.getUrl().regex(URL_LIST).match()) {
            page.addTargetRequests(page.getHtml().xpath("//ul[@class=\"newlist\"]").links().regex(URL_POST).all());
            page.addTargetRequests(page.getHtml().xpath("//ul[@class=\"pagernums\"]").links().regex(URL_NEXT).all());
            //文章页
        }else if (page.getUrl().regex(URL_POST).match()) {
			
		} else {
        	//评论ID
            page.putField("评论ID", "");
            //评论人（用户名）
            page.putField("评论人", HtmlUtil.getTextFromHtml(page.getHtml().xpath("//span[@class='zwnick']").all()));
            //影响力
            page.putField("影响力", "");
            //吧龄
            page.putField("吧龄", "");
            //评论时间
            page.putField("评论时间", HtmlUtil.getTextFromHtml(page.getHtml().xpath("//div[@class='zwlitime']").all()));
            //评论内容
            page.putField("评论内容", HtmlUtil.getTextFromHtml(page.getHtml().xpath("//div[@class='zwlitext stockcodec']").all()));
            //被赞数
            page.putField("被赞数", "");
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new GuBaCommentPageProcessor())
        	.addUrl("http://guba.eastmoney.com/news,cjpl,258868572_2.html")
        	.addPipeline(new JsonFilePipeline("G:/webmagic/"))
        	.thread(5)
            .run();
    }
}